#!/bin/bash

#
# sfv -- by Dario Berzano <dario.berzano@gmail.com>
#
# Part of the lfscripts suite -- http://lfscripts.googecode.com/
#
# Checks checksums in sfv format (for those who still use them instead of better
# systems)
#

TOT=0
ERR=0

for SFV in *.sfv
do
  if [ -r "$SFV" ]; then

      while read L
      do

        LEN=${#L}
        let S=LEN-9
        XSUM=${L:$S:8}
        let S--
        FILE=${L:0:$S}

        if [ ! -r "$FILE" ]; then
          echo "File $FILE does not exist!"
        else
          CSUM=`crc32 "$FILE"`
          if [ $? != 0 ]; then
            echo "Operation aborted for errors on $FILE"
            exit 2
          fi
        fi

        # Check
        if [ "$CSUM" != "$XSUM" ]; then
          echo "$FILE NOT OK"
          let ERR++
        fi

        let TOT++

      done < "$SFV"

      # Summary
      if [ $ERR -gt 0 ]; then
        echo "==> There were errors on $ERR files out of $TOT"
        exit 1
      else
        echo "==> All $TOT files are OK."
        exit 0
      fi

    # not reached -- break
  fi
done
